package com.ruoyi.syf.handler.task.strategy;

import com.ruoyi.common.utils.CronUtil;
import com.ruoyi.common.utils.MyCalendar;
import com.ruoyi.syf.common.constant.TaskType;
import com.ruoyi.syf.handler.task.TaskStrategy;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;

/**
 * 隐患排查定时任务策略-每日
 *
 * @author yr
 * @date 2024-07-31
 */
@Service
public class DailyTaskStrategy implements TaskStrategy {
    @Override
    public String getTaskType() {
        return TaskType.DAILY;
    }

    @Override
    public String toCronExpression(int num, String timeUnit, Date startTime) {
        MyCalendar calendar = new MyCalendar(startTime);
        return CronUtil.toCronExpressionDaily(calendar);
    }

    @Override
    public Date getNextBeginTime(Date date, Date startTime, Integer cycle, String cycleUnit) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, 1);
        return calendar.getTime();
    }

    @Override
    public Date getLastBeginTime(Date startTime, Integer cycle, String cycleUnit) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startTime);
        calendar.add(Calendar.DATE, -1);
        return calendar.getTime();
    }

    @Override
    public Date getRecentBeginTime(Date startTime, Integer cycle, String cycleUnit) {
        return getTimeByCycle(startTime,System.currentTimeMillis());
    }

    private Date getTimeByCycle(Date startTime, long time) {
        Date dateByCycle = getNextBeginTime(startTime,null,null,null);
        if (dateByCycle.getTime() <= time) {
            return getTimeByCycle(dateByCycle, time);
        }
        return dateByCycle;
    }

}
